import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:tracker/common/widget/button/gradient_button.dart';
import 'package:tracker/pages/home/phone_book/controller/phone_book_controller.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/toast_utils.dart';

/// 电话簿页面
class PhoneBookPage extends HookConsumerWidget {
  const PhoneBookPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    var state = ref.watch(phoneBookControllerProvider);
    state.when(
      data: (value) {
        ToastUtils.dismissLoading();
      },
      loading: () {
        ToastUtils.showLoading();
      },
      error: (error, stack) {
        ToastUtils.showToast(error.toString());
      },
    );
    // 边距
    const double margin = 16;

    useEffect(() {
      WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
        ref.read(phoneBookControllerProvider.notifier).getContactList();
      });
      return null;
    }, []);

    return Scaffold(
      body: Stack(
        children: [
          Container(
            height: double.infinity,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/page_bg.png'),
                fit: BoxFit.cover,
              ),
            ),
          ),
          CustomScrollView(
            slivers: [
              SliverAppBar(
                title: const Text(
                  '电话簿',
                  style: TextStyle(color: Colors.white),
                ),
                centerTitle: true,
                backgroundColor: Colors.transparent,
                foregroundColor: Colors.white,
                expandedHeight: 200.0,
                bottom: PreferredSize(
                  preferredSize: const Size.fromHeight(200.0),
                  child: _buildTopView(),
                ),
              ),
              SliverPadding(
                padding: const EdgeInsets.only(bottom: 20),
                sliver: SliverList(
                  delegate: SliverChildBuilderDelegate(
                    (context, index) {
                      return _buildCell(index);
                    },
                    childCount: state.value!.contactList.length,
                  ),
                ),
              ),
              // "添加"按钮
              SliverToBoxAdapter(
                child: Container(
                  margin: const EdgeInsets.only(left: margin, right: margin, bottom: 90),
                  child: ElevatedButton(
                    onPressed: () {
                      // 最多添加6个号码
                      if (state.value!.contactList.length >= 6) {
                        ToastUtils.showToast('最多添加6个号码');
                        return;
                      }
                      _showInputDialog(context);
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.white,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                    child: Container(
                      height: 50,
                      alignment: Alignment.center,
                      child: Text(
                        '添加号码',
                        style: TextStyle(
                          color: AppTheme.themeConfig.primaryTextColor,
                          fontSize: 17,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
          Positioned(
            bottom: 20,
            left: 16,
            right: 16,
            child: Container(
              child: ElevatedButton(
                onPressed: () {
                  ref.read(phoneBookControllerProvider.notifier).submit();
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppTheme.themeConfig.primaryColor,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                child: Container(
                  height: 50,
                  alignment: Alignment.center,
                  child: Text(
                    '立即更新设备电话簿',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 17,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCell(int index) {
    return Consumer(
        key: ValueKey(index),
        builder: (context, ref, child) {
          // 一共有4个操作按钮，根据屏幕宽度计算每个按钮的宽度
          double buttonWidth = (MediaQuery.of(context).size.width - 16 * 2 - 12 * 3) / 4;
          // 如果宽度大于80，就取80
          buttonWidth = buttonWidth > 70 ? 70 : buttonWidth;
          // 获取联系人
          var contact = ref.watch(phoneBookControllerProvider).value!.contactList[index];
          return Container(
            margin: const EdgeInsets.only(left: 16, right: 16, top: 16),
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
            ),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      contact.name ?? '',
                      style: TextStyle(
                        color: AppTheme.themeConfig.primaryTextColor,
                        fontSize: 17,
                      ),
                    ),
                    Text(
                      contact.phone ?? '',
                      style: TextStyle(
                        color: AppTheme.themeConfig.primaryTextColor,
                        fontSize: 17,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                // 上移、下移、编辑、删除按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    GradientButton(
                      text: '上移',
                      onPressed: () {
                        ref.read(phoneBookControllerProvider.notifier).moveUpContact(index);
                      },
                      gradientColors: [ColorUtils.hexToColor('#3CB7FD'), ColorUtils.hexToColor('#3378FD')],
                      width: buttonWidth,
                    ),
                    GradientButton(
                      text: '下移',
                      onPressed: () {
                        ref.read(phoneBookControllerProvider.notifier).moveDownContact(index);
                      },
                      gradientColors: [ColorUtils.hexToColor('#3CB7FD'), ColorUtils.hexToColor('#3378FD')],
                      width: buttonWidth,
                    ),
                    GradientButton(
                      text: '修改',
                      onPressed: () {
                        _showInputDialog(context, isEdit: true, index: index);
                      },
                      gradientColors: [ColorUtils.hexToColor('#FF923A'), ColorUtils.hexToColor('#FFC71C')],
                      width: buttonWidth,
                    ),
                    GradientButton(
                      text: '删除',
                      onPressed: () {
                        ref.read(phoneBookControllerProvider.notifier).deleteContact(index);
                      },
                      gradientColors: [ColorUtils.hexToColor('#F7422D'), ColorUtils.hexToColor('#FB6E52')],
                      width: buttonWidth,
                    ),
                  ],
                )
              ],
            ),
          );
        });
  }

  _showInputDialog(BuildContext context, {bool isEdit = false, int index = -1}) {
    // 输入姓名、电话号码
    TextEditingController nameController = TextEditingController();
    TextEditingController phoneController = TextEditingController();
    final title = isEdit ? '修改号码' : '添加号码';
    showDialog(
      context: context,
      builder: (context) {
        return Consumer(builder: (ctx, ref, child) {
          final state = ref.watch(phoneBookControllerProvider);
          final contact = isEdit ? state.value!.contactList[index] : null;
          if (isEdit) {
            nameController.text = contact!.name ?? '';
            phoneController.text = contact.phone ?? '';
          }
          return AlertDialog(
            title: Text(title),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextField(
                  controller: nameController,
                  decoration: const InputDecoration(
                    labelText: '姓名',
                  ),
                  inputFormatters: [
                    // 最大长度30位
                    LengthLimitingTextInputFormatter(8),
                  ],
                ),
                // 电话号码、只能输入数字
                TextField(
                  controller: phoneController,
                  keyboardType: TextInputType.number,
                  decoration: const InputDecoration(
                    labelText: '号码',
                  ),
                  inputFormatters: [
                    FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),
                    // 最大长度11位
                    LengthLimitingTextInputFormatter(11),
                  ],
                ),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: const Text('取消'),
              ),
              Consumer(builder: (context, ref, child) {
                return TextButton(
                  onPressed: () {
                    // 校验姓名
                    var name = nameController.text;
                    if (name.isEmpty) {
                      ToastUtils.showToast('请输入姓名');
                      return;
                    }
                    // 校验号码是正确的电话号码
                    var phone = phoneController.text;
                    if (phone.isEmpty) {
                      ToastUtils.showToast('请输入号码');
                      return;
                    }
                    final state = ref.read(phoneBookControllerProvider.notifier);
                    if (isEdit) {
                      // 编辑
                      state.updateContact(index, name, phone);
                    } else {
                      // 添加
                      state.addContact(name, phone);
                    }
                    // 添加号码
                    Navigator.of(context).pop();
                  },
                  child: const Text('保存'),
                );
              }),
            ],
          );
        });
      },
    );
  }

  Container _buildTopView() {
    return Container(
      // color: Colors.red,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const Image(image: AssetImage('assets/images/home/phone_book_icon.png'), width: 133, height: 130),
          Expanded(
            child: Container(
              height: 200,
              padding: const EdgeInsets.only(top: 12, right: 12),
              // 占满
              decoration: const BoxDecoration(
                  // color: AppTheme.themeConfig.primaryColor,
                  ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text(
                    '电话簿介绍',
                    style: TextStyle(
                      color: AppTheme.themeConfig.primaryTextColor,
                      fontSize: 17,
                    ),
                  ),
                  SizedBox(height: 20),
                  Text(
                    '设置电话簿之后设备才能接打电话，其他号码来电时设备自动拒接。\nSOS报警时设备顺序拨打电话簿的号码直到电话接通。\n注意设备需插入带有通话功能的电话卡。',
                    style: TextStyle(
                      color: AppTheme.themeConfig.primaryTextColor,
                      fontSize: 14,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
